<template>
  <div class="ewe-pregnancy-examination-add-container">
    <!-- 操作按钮区 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleSave">保存</el-button>
      <el-button @click="handleCancel">撤销</el-button>
    </div>

    <!-- 表头区域 -->
    <el-card class="header-card" shadow="never">
      <el-form :model="headerForm" label-width="90px" class="header-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="负责人" required>
              <el-select v-model="headerForm.ResponsiblePerson" placeholder="请选择负责人" filterable>
                <el-option v-for="item in userList" :key="item.UserId" :label="item.UserName" :value="item.UserId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="妊检日期" required>
              <el-date-picker v-model="headerForm.PregnancyCheckDate" type="date" placeholder="请选择妊检日期" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据号">
              <div style="display: flex; align-items: center; gap: 8px;">
                <el-input v-model="headerForm.DocumentNumber" placeholder="自动生成" readonly />
                <el-button type="primary" size="small" @click="regenerateDocumentNumber">重新生成</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="流水号">
              <div style="display: flex; align-items: center; gap: 8px;">
                <el-input v-model="headerForm.SerialNumber" placeholder="自动生成" readonly />
                <el-button type="primary" size="small" @click="regenerateSerialNumber">重新生成</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 表体区域 -->
    <el-card class="body-card" shadow="never">
      <el-table :data="tableData" border stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="EarTag" label="种母耳号" width="120" align="center" required>
          <template #default="scope">
            <el-select v-model="scope.row.EarTag" placeholder="请选择耳号" size="small" filterable>
              <el-option v-for="item in earNumberList" :key="item.Id" :label="item.Name" :value="item.Id" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="PregnancyResult" label="妊检结果" width="120" align="center" required>
          <template #default="scope">
            <el-select v-model="scope.row.PregnancyResult" placeholder="请选择妊检结果" size="small">
              <el-option label="阳性" value="阳性" />
              <el-option label="阴性" value="阴性" />
              <el-option label="待定" value="待定" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="PregnancyMethod" label="妊检方法" width="120" align="center" required>
          <template #default="scope">
            <el-select v-model="scope.row.PregnancyMethod" placeholder="请选择妊检方法" size="small">
              <el-option label="公羊试情" value="公羊试情" />
              <el-option label="人工检查" value="人工检查" />
              <el-option label="B超检查" value="B超检查" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="FetusCount" label="胎数" width="100" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.FetusCount" :min="0" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="GestationDays" label="妊娠天数" width="100" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.GestationDays" :min="0" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="CurrentPen" label="当前栏位" width="120" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.CurrentPen" placeholder="请选择栏位" size="small">
              <el-option v-for="item in buildingList" :key="item.BuildingId" :label="item.House_name" :value="item.BuildingId" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="CurrentStall" label="当前栏号" width="120" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.CurrentStall" placeholder="请选择栏号" size="small">
              <el-option v-for="item in penList" :key="item.Id" :label="item.Name" :value="item.Id" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="TransferPen" label="转入栏位" width="120" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.TransferPen" placeholder="请选择栏位" size="small">
              <el-option v-for="item in buildingList" :key="item.BuildingId" :label="item.House_name" :value="item.BuildingId" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="TransferStall" label="转入栏号" width="120" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.TransferStall" placeholder="请选择栏号" size="small">
              <el-option v-for="item in penList" :key="item.Id" :label="item.Name" :value="item.Id" />
              </el-select>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="80" align="center">
          <template #default="scope">
            <el-button link type="danger" size="small" @click="removeRow(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
        
      <!-- 表格操作按钮 -->
      <div class="table-actions">
        <el-button type="primary" @click="addRow" icon="Plus">+ 增行</el-button>
        <el-button type="danger" @click="removeLastRow" icon="Minus">- 删行</el-button>
      </div>
    </el-card>

    <!-- 备注区域 -->
    <el-card class="remark-card" shadow="never">
      <el-form-item label="备注">
        <el-input v-model="headerForm.Remark" type="textarea" placeholder="请输入备注信息" />
        </el-form-item>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { Sheep_BreedingWrite, serviceRead, Sheep_BreedingRead } from '../../utils/Interceptors'

const router = useRouter()

// 下拉数据
const userList = ref<any[]>([])
const buildingList = ref<any[]>([])
const penList = ref<any[]>([])
const earNumberList = ref<any[]>([]) // 新增耳号列表

// 表头表单数据
const headerForm = reactive({
  ResponsiblePerson: '',
  PregnancyCheckDate: '',
  DocumentNumber: '',
  SerialNumber: '',
  Remark: ''
})

// 表体数据
const tableData = ref([
  {
    EarTag: null,
  PregnancyResult: '',
  PregnancyMethod: '',
    FetusCount: null,
    GestationDays: null,
  CurrentPen: '',
  CurrentStall: '',
  TransferPen: '',
  TransferStall: '',
    Status: '待审核'
  }
])

// 增加行
const addRow = () => {
  tableData.value.push({
    EarTag: null,
    PregnancyResult: '',
    PregnancyMethod: '',
    FetusCount: null,
    GestationDays: null,
    CurrentPen: '',
    CurrentStall: '',
    TransferPen: '',
    TransferStall: '',
    Status: '待审核'
  })
}

// 删除指定行
const removeRow = (index: number) => {
  if (tableData.value.length > 1) {
    tableData.value.splice(index, 1)
    } else {
    ElMessage.warning('至少保留一行')
  }
}

// 删除最后一行
const removeLastRow = () => {
  if (tableData.value.length > 1) {
    tableData.value.pop()
  } else {
    ElMessage.warning('至少保留一行')
    }
}

// 生成单据号
const generateDocumentNumber = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  
  return `RJ${year}${month}${day}${hours}${minutes}${seconds}${random}`
}

// 生成流水号
const generateSerialNumber = () => {
  const now = new Date()
  const timestamp = now.getTime()
  const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
  
  return `LS${timestamp}${random}`
}

// 重新生成单据号
const regenerateDocumentNumber = () => {
  headerForm.DocumentNumber = generateDocumentNumber()
  ElMessage.success('单据号已重新生成')
}

// 重新生成流水号
const regenerateSerialNumber = () => {
  headerForm.SerialNumber = generateSerialNumber()
  ElMessage.success('流水号已重新生成')
}

// 保存
const handleSave = async () => {
  // 验证表头必填项
  if (!headerForm.ResponsiblePerson) {
    ElMessage.error('请选择负责人')
    return
  }
  if (!headerForm.PregnancyCheckDate) {
    ElMessage.error('请选择妊检日期')
    return
  }

  // 验证表体数据
  for (let i = 0; i < tableData.value.length; i++) {
    const row = tableData.value[i]
    if (!row.EarTag || row.EarTag === '' || row.EarTag === 0) {
      ElMessage.error(`第${i + 1}行请选择种母耳号`)
      return
    }
    if (!row.PregnancyResult) {
      ElMessage.error(`第${i + 1}行妊检结果不能为空`)
      return
    }
    if (!row.PregnancyMethod) {
      ElMessage.error(`第${i + 1}行妊检方法不能为空`)
      return
    }
  }

  try {
    // 自动生成单据号和流水号
    if (!headerForm.DocumentNumber) {
      headerForm.DocumentNumber = generateDocumentNumber()
    }
    if (!headerForm.SerialNumber) {
      headerForm.SerialNumber = generateSerialNumber()
    }

    // 获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const userName = userInfo.UserName || '系统用户'
    const currentTime = new Date().toISOString()

    // 只处理第一行数据，参考其他页面的提交方式
    const firstRow = tableData.value[0]
    
    // 构建提交数据 - 根据错误信息调整字段名和格式
    const payload = {
      ear_tag: firstRow.EarTag ? String(firstRow.EarTag) : '',
      pregnancy_check_date: headerForm.PregnancyCheckDate ? headerForm.PregnancyCheckDate : new Date().toISOString().split('T')[0],
      pregnancy_result: firstRow.PregnancyResult || '',
      pregnancy_method: firstRow.PregnancyMethod || '',
      fetus_count: firstRow.FetusCount ? parseInt(firstRow.FetusCount) : 0,
      gestation_days: firstRow.GestationDays ? parseInt(firstRow.GestationDays) : 0,
      current_pen: firstRow.CurrentPen ? String(firstRow.CurrentPen) : '',
      current_stall: firstRow.CurrentStall ? String(firstRow.CurrentStall) : '',
      transfer_pen: firstRow.TransferPen ? String(firstRow.TransferPen) : '',
      transfer_stall: firstRow.TransferStall ? String(firstRow.TransferStall) : '',
      status: '待审核',
      document_number: headerForm.DocumentNumber || generateDocumentNumber(),
      responsible_person: String(headerForm.ResponsiblePerson || ''),
      creator: userName || '系统用户',
      create_time: currentTime,
      modifier: userName || '系统用户',
      modify_time: currentTime,
      approver: userName || '系统用户',
      approval_time: currentTime,
      record_type: '常规', 
      remark: headerForm.Remark || ''
    }
    
    console.log('提交数据:', JSON.stringify(payload)) // 打印完整JSON字符串
    console.log('ear_tag类型:', typeof payload.ear_tag, payload.ear_tag)
    
    const res = await Sheep_BreedingWrite.post('/api/PregnancyExamination/create', payload)
    console.log('API响应:', res)
      if (res.data && res.data.code === 200) {
      ElMessage.success('保存成功')
        router.push('/EwePregnancyExamination')
      } else {
      ElMessage.error(res.data?.msg || '保存失败')
      console.error('保存失败详情:', res.data)
      }
    } catch (error: any) {
    console.error('请求异常:', error)
    console.error('请求异常详情:', error.response?.data)
    console.error('请求状态码:', error.response?.status)
    console.error('请求错误信息:', error.message)
    ElMessage.error(error?.response?.data?.msg || error?.message || '保存失败')
  }
}

// 撤销
const handleCancel = () => {
  router.push('/EwePregnancyExamination')
        }

// 获取用户列表
const fetchUserList = () => {
  serviceRead.get('/api/User/SraechUser').then(res => {
    if (res.data && res.data.code === 200) {
      userList.value = res.data.PageData || []
      } else {
      userList.value = []
    }
  })
}

// 获取栋舍和栏位列表 
const fetchBuildingAndPenList = () => {
  // 获取栏位列表（作为当前栏位和转入栏位）
  Sheep_BreedingRead.get('/api/Sheepfarm/SearchBuildingManagement', {
    params: { PageIndex: 1, PageSize: 100 }
  }).then(res => {
    console.log('栏位API返回:', res.data)
    if (res.data && res.data.code === 200) {
      buildingList.value = res.data.PageData || []
      console.log('栏位列表:', buildingList.value)
    } else {
      buildingList.value = []
      console.log('栏位API失败:', res.data)
    }
  }).catch(err => {
    console.error('栏位API错误:', err)
    buildingList.value = []
  })

  // 获取栏号列表（作为当前栏号和转入栏号）
  Sheep_BreedingRead.get('/api/EliminationInfo/GetFieldManagementIdName').then(res => {
    console.log('栏号API返回:', res.data)
    if (res.data && res.data.code === 200) {
      penList.value = res.data.data || []
      console.log('栏号列表:', penList.value)
    } else {
      penList.value = []
      console.log('栏号API失败:', res.data)
      }
  }).catch(err => {
    console.error('栏号API错误:', err)
    penList.value = []
  })
}

// 获取耳号列表
const fetchEarNumberList = () => {
  Sheep_BreedingRead.get('/api/EliminationInfo/GetSheepFilesIdEarNumber').then(res => {
    console.log('耳号API返回:', res.data)
    if (res.data && res.data.code === 200) {
      earNumberList.value = res.data.data || []
      console.log('耳号列表:', earNumberList.value)
      // 打印第一个耳号的数据结构
      if (earNumberList.value.length > 0) {
        console.log('第一个耳号数据结构:', earNumberList.value[0])
        console.log('第一个耳号的所有字段:', Object.keys(earNumberList.value[0]))
  }
    } else {
      earNumberList.value = []
      console.log('耳号API失败:', res.data)
    }
  }).catch(err => {
    console.error('耳号API错误:', err)
    earNumberList.value = []
  })
}

onMounted(() => {
  fetchUserList()
  fetchBuildingAndPenList()
  fetchEarNumberList() // 在页面加载时获取耳号列表
  
  // 页面加载时自动生成单据号和流水号
  headerForm.DocumentNumber = generateDocumentNumber()
  headerForm.SerialNumber = generateSerialNumber()
})
</script>

<style scoped>
.ewe-pregnancy-examination-add-container {
  min-height: 100vh;
  background: #f7f8fa;
  padding: 24px;
}

.action-bar {
  margin-bottom: 16px;
}

.header-card {
  margin-bottom: 18px;
}

.header-form {
  padding: 12px 0;
}

.body-card {
  margin-bottom: 12px;
}

.table-actions {
  margin-top: 8px;
  display: flex;
  gap: 8px;
}

.remark-card {
  margin-top: 12px;
}
</style> 